var path = require('path');
var fs = require('fs');

/** 
 * 路由自动加载,遍历所有文件和文件夹,对index.js的文件做特殊处理,放到第一位加载
 */
function iterationFolder(folderPath) {
    var routers = [];
    //对index.js做特殊处理,放到第一位
    var strs = fs.readdirSync(folderPath);
    var index = strs.indexOf('index.js');
    if (index > 0) {
        //index.js放到第一位,优先加载,因为默认在index.js中注入了上游变量
        var temp = strs[0];
        strs[0] = strs[index];
        strs[index] = temp;
    }
    strs.forEach(function (file) {
        var filePath = path.join(folderPath, './' + file);
        if (filePath === __filename) return;
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            routers.push(filePath);
        } else if (stat.isDirectory()) {
            routers = routers.concat(iterationFolder(filePath));
        }
    });
    return routers;
}

function registerRoutes(app) {
    iterationFolder(__dirname)
        .forEach(function (file) {
            var route = require(file);
            app.use(route);
        });
}

module.exports = registerRoutes;
